<template>
	<div class="page-container">
		<!-- 顶部筛选区域 -->
		<div class="filter-container">
			<div class="filter-content">
				<!-- 搜索框 -->
				<div class="search-wrapper">
					<el-input v-model="searchParams.name" placeholder="请输入分类名称" class="search-input">
						<template #prefix>
							<el-icon>
								<search />
							</el-icon>
						</template>
					</el-input>
				</div>

				<!-- 排序控件组 -->
				<div class="sort-group">
					<div class="sort-item">
						<div class="filter-label">创建时间</div>
						<el-select v-model="createdSort" placeholder="创建时间" class="full-width custom-select">
							<el-option label="不生效" value="none" />
							<el-option label="↑ 升序" :value="true" />
							<el-option label="↓ 降序" :value="false" />
						</el-select>
					</div>
					<div class="sort-item">
						<div class="filter-label">修改时间</div>
						<el-select v-model="updatedSort" placeholder="修改时间" class="full-width custom-select">
							<el-option label="不生效" value="none" />
							<el-option label="↑ 升序" :value="true" />
							<el-option label="↓ 降序" :value="false" />
						</el-select>
					</div>
				</div>

				<!-- 操作按钮 -->
				<div class="action-buttons">
					<el-button type="primary" class="action-button" @click="handleSearch">
						<el-icon class="button-icon">
							<search />
						</el-icon>
						搜索
					</el-button>
					<el-button class="action-button" @click="handleReset">
						<el-icon class="button-icon">
							<refresh />
						</el-icon>
						清空
					</el-button>
				</div>
			</div>
		</div>

		<!-- 数据表格区域 -->
		<div class="table-container">
			<el-table ref="multipleTableRef" @selection-change="handleSelectionChange" v-loading="loading"
				:data="tableData" row-key="id" stripe style="width: 100%" :max-height="tableMaxHeight">
				<el-table-column type="selection" width="55" />
				<el-table-column prop="name" label="分类名称" />
				<el-table-column prop="deleted" label="是否删除">
					<template #default="{ row }">
						<el-tag :type="row.deleted === 0 ? 'success' : 'danger'" effect="light" class="status-tag">
							{{ row.deleted === 0 ? '未删除' : '已删除' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createdAt" label="创建时间" width="180" />
				<el-table-column prop="updatedAt" label="修改时间" width="180" />

				<el-table-column label="操作" width="180">
					<template #default="{ row }">
						<el-button size="small" @click="handleDetail(row.id)" class="action-icon" type="primary">
							<el-icon>
								<document />
							</el-icon>
						</el-button>
						<el-button size="small" @click="handleEdit(row.id)" class="action-icon">
							<el-icon>
								<edit />
							</el-icon>
						</el-button>
						<el-button size="small" @click="handleDelete(row.id)" class="action-icon" type="danger">
							<el-icon>
								<delete />
							</el-icon>
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!-- 批量操作按钮 -->
		<div class="batch-actions" v-if="multipleSelection.length > 0">
			<el-button @click="toggleSelection()">取消选择</el-button>
			<el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
		</div>
		<!-- 分页区域 -->
		<div class="pagination" v-else>
			<el-pagination :current-page="searchParams.pageNo" :page-size="searchParams.pageSize"
				:page-sizes="[10, 20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
				:total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>
	</div>
</template>

<script>
	export default {
		name: 'ShoppingCategoriesView',
	};
</script>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		computed,
				onUnmounted
	} from 'vue';
	import {
		Search,
		Refresh,
		Edit,
		Delete,
		Document
	} from '@element-plus/icons-vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import {
		getCategoriesPage,
		deleteCategories
	} from '@/api/shoppingCategories.js';
	import {
		useRouter
	} from 'vue-router'

	const router = useRouter()
	const total = ref(0);
	const loading = ref(false);

	//多选
	const multipleTableRef = ref()
	const multipleSelection = ref([])

	/**
	 * 初始化搜索参数
	 */
	const searchParams = reactive({
		name: '', // 搜索关键词
		pageNo: 1, // 当前页码
		pageSize: 10, // 每页数量

		// 创建时间排序相关
		createdIsAsc: false, // 是否升序
		createdEnabled: false, // 是否启用排序

		// 更新时间排序相关
		updatedIsAsc: false, // 是否升序
		updatedEnabled: false, // 是否启用排序
	})
	/**
	 * 表格高度
	 */
	const tableMaxHeight = ref(null)
	/**
	 * 表格数据
	 */
	const tableData = ref([]);

	/**
	 * 计算属性：创建时间排序
	 */
	const createdSort = computed({
		get() {
			return searchParams.createdEnabled ? searchParams.createdIsAsc : 'none';
		},
		set(val) {
			if (val === 'none') {
				searchParams.createdEnabled = false;
			} else {
				searchParams.createdEnabled = true;
				searchParams.createdIsAsc = val;
			}
		},
	});

	/**
	 * 计算属性：修改时间排序
	 */
	const updatedSort = computed({
		get() {
			return searchParams.updatedEnabled ? searchParams.updatedIsAsc : 'none';
		},
		set(val) {
			if (val === 'none') {
				searchParams.updatedEnabled = false;
			} else {
				searchParams.updatedEnabled = true;
				searchParams.updatedIsAsc = val;
			}
		},
	});

	/**
	 * API请求
	 */
	const fetchData = async () => {
		loading.value = true;
		try {
			const res = await getCategoriesPage(searchParams)

			if (res.code === 200) {
				tableData.value = res.data.records;
				total.value = res.data.total;
				ElMessage.success(res.message || '获取数据成功');
			} else {
				ElMessage.error(res.message || '获取数据失败');
			}
		} catch (error) {
			ElMessage.error('请求失败: ' + error.message);
			console.log('请求失败: ', error.message);
			console.log('请求失败: ', error);
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 处理搜索
	 */
	const handleSearch = () => {
		searchParams.pageNo = 1;
		fetchData();
	};

	/**
	 * 处理重置
	 */
	const handleReset = () => {
		searchParams.name = '';
		searchParams.pageNo = 1;

		// 重置排序相关
		searchParams.createdIsAsc = false;
		searchParams.createdEnabled = false;
		searchParams.updatedIsAsc = false;
		searchParams.updatedEnabled = false;

		handleSearch();
	};

	/**
	 * 分页大小变化
	 */
	const handleSizeChange = (val) => {
		searchParams.pageSize = val
		fetchData();
	}

	/**
	 * 当前页变化
	 */
	const handleCurrentChange = (val) => {
		searchParams.pageNo = val
		fetchData();
	}
	
	/**
	 * 处理详情
	 */
	const handleDetail = (id) => {
		router.push(`/category/${id}`)
	};
	
	/**
	 * 处理编辑
	 */
	const handleEdit = (id) => {
		router.push(`/category/edit/${id}`)
	};

	/**
	 * 处理删除
	 */
	const handleDelete = async (id) => {
		console.log('删除', id);
		try {
			await ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
				type: 'warning'
			})
			await deleteCategories(id)
			ElMessage.success('删除成功')
			await fetchData()
		} catch (error) {
			console.log('取消删除')
		}
	};

	/**
	 * 多选处理
	 */
	const handleSelectionChange = (val) => {
		multipleSelection.value = val
	}

	/**
	 * 清除选择
	 */
	const toggleSelection = (rows) => {
		if (rows) {
			rows.forEach((row) => {
				multipleTableRef.value.toggleRowSelection(row, undefined)
			})
		} else {
			multipleTableRef.value.clearSelection()
		}
	}

	/**
	 * 批量删除
	 */
	const handleBatchDelete = async () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请至少选择一项')
			return
		}

		try {
			await ElMessageBox.confirm(`确定要删除选中的${multipleSelection.value.length}项吗？`, '提示', {
				type: 'warning'
			})
			const ids = multipleSelection.value.map(item => item.id)
			// 这里需要根据实际情况修改批量删除接口调用
			for (const id of ids) {
				await deleteCategories(id)
			}
			ElMessage.success('批量删除成功')
			toggleSelection()
			await fetchData()
		} catch (error) {
			console.log(error);
			console.log('取消批量删除')
		}
	}
	
	/**
	 * 计算表格高度
	 */ 
	const calculateTableHeight = () => {
		// 根据你的布局调整这个计算逻辑
		// 例如：视窗高度 - 顶部筛选区域高度 - 分页区域高度 - 其他元素高度
		const windowHeight = window.innerHeight
		const filterHeight = 200 // 顶部筛选区域估计高度
		const paginationHeight = 60 // 分页区域估计高度
		const otherElementsHeight = 40 // 其他元素估计高度

		tableMaxHeight.value = windowHeight - filterHeight - paginationHeight - otherElementsHeight
	}
	
	// 初始化数据
	onMounted(() => {
		calculateTableHeight()
		window.addEventListener('resize', calculateTableHeight)
		fetchData();
	});
	
	onUnmounted(() => {
		window.removeEventListener('resize', calculateTableHeight)
	})
</script>

<style scoped>
	.page-container {
		background-color: #f9fafb;
		/* 继承父容器高度 */
		height: 100%;
		min-height: 0;
		overflow-y: auto;
	}

	.pagination {
		position: static;
		overflow: visible;
	}

	.batch-actions {
		margin: 20px 0;
		flex-shrink: 0;
	}

	.filter-container {
		padding: 24px;
		background-color: #f3f4f6;
		border-radius: 8px;
		box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
	}

	.filter-content {
		display: flex;
		flex-direction: column;
		gap: 24px;
	}

	.search-wrapper {
		width: 100%;
		display: flex;
		align-items: center;
	}

	.search-input {
		width: 33.33%;
	}

	.search-input :deep(.el-input__inner) {
		border-radius: 20px;
	}

	.sort-group {
		display: flex;
		gap: 40px;
	}

	.sort-item {
		width: 33.33%;
	}

	.full-width {
		width: 100%;
	}

	.filter-group {
		display: flex;
		gap: 40px;
	}

	.filter-item {
		width: 50%;
	}

	.filter-label {
		margin-bottom: 8px;
		font-size: 14px;
		color: #6b7280;
	}

	.action-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 16px;
	}

	.action-button {
		border-radius: 20px;
		white-space: nowrap;
	}

	.button-icon {
		margin-right: 4px;
	}

	.table-container {
		margin-top: 24px;
	}

	:deep(.el-table .cell) {
		padding-left: 12px;
		padding-right: 12px;
	}

	:deep(.el-table th.el-table__cell) {
		background-color: #f8f8f9;
	}

	:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
		background-color: #fafafa;
	}

	:deep(.el-radio-button:not(.is-active) .el-radio-button__inner) {
		border-color: #dcdfe6;
		color: #606266;
	}

	.thumbnail-image {
		width: 80px;
		height: 80px;
		border-radius: 4px;
	}

	.status-tag {
		border-radius: 20px;
	}

	.action-icon {
		border-radius: 20px;
	}

	/* 修复下拉选择器样式 */
	:deep(.custom-select .el-input__inner) {
		background-color: white !important;
		border-color: #dcdfe6 !important;
	}

	:deep(.custom-select .el-input__inner:hover) {
		border-color: #409eff !important;
	}

	:deep(.custom-select .el-input.is-focus .el-input__inner) {
		border-color: #409eff !important;
		background-color: #e6f7ff !important;
	}

	/* 修复单选按钮组样式 */
	:deep(.custom-radio-group .el-radio-button__inner) {
		background-color: white !important;
		border-color: #dcdfe6 !important;
		color: #606266 !important;
		margin: 2px !important;
	}

	:deep(.custom-radio-group .el-radio-button__inner:hover) {
		color: #409eff !important;
	}

	:deep(.custom-radio-group .el-radio-button.is-active .el-radio-button__inner) {
		background-color: #409eff !important;
		border-color: #409eff !important;
		color: white !important;
		box-shadow: none !important;
	}

	:deep(.custom-radio-group .el-radio-button:first-child .el-radio-button__inner) {
		border-left: 1px solid #dcdfe6 !important;
	}

	:deep(.custom-radio-group .el-radio-button:last-child .el-radio-button__inner) {
		border-radius: 0 4px 4px 0 !important;
	}
</style>